package api

import (
	"net/http"

	"example.com/rest/example/dao"
	"example.com/rest/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configGenresRouter(router *httprouter.Router) {
	router.GET("/genres", GetAllGenres)
	router.POST("/genres", AddGenres)
	router.GET("/genres/:argGenreID", GetGenres)
	router.PUT("/genres/:argGenreID", UpdateGenres)
	router.DELETE("/genres/:argGenreID", DeleteGenres)
}

func configGinGenresRouter(router gin.IRoutes) {
	router.GET("/genres", ConverHttprouterToGin(GetAllGenres))
	router.POST("/genres", ConverHttprouterToGin(AddGenres))
	router.GET("/genres/:argGenreID", ConverHttprouterToGin(GetGenres))
	router.PUT("/genres/:argGenreID", ConverHttprouterToGin(UpdateGenres))
	router.DELETE("/genres/:argGenreID", ConverHttprouterToGin(DeleteGenres))
}

// GetAllGenres is a function to get a slice of record(s) from genres table in the main database
// @Summary Get list of Genres
// @Tags Genres
// @Description GetAllGenres is a handler to get a slice of record(s) from genres table in the main database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Genres}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /genres [get]
// http "http://localhost:8080/genres?page=0&pagesize=20" X-Api-User:user123
func GetAllGenres(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "genres", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllGenres(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetGenres is a function to get a single record from the genres table in the main database
// @Summary Get record from table Genres by  argGenreID
// @Tags Genres
// @ID argGenreID
// @Description GetGenres is a function to get a single record from the genres table in the main database
// @Accept  json
// @Produce  json
// @Param  argGenreID path int true "GenreId"
// @Success 200 {object} model.Genres
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /genres/{argGenreID} [get]
// http "http://localhost:8080/genres/1" X-Api-User:user123
func GetGenres(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argGenreID, err := parseInt32(ps, "argGenreID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "genres", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetGenres(ctx, argGenreID)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddGenres add to add a single record to genres table in the main database
// @Summary Add an record to genres table
// @Description add to add a single record to genres table in the main database
// @Tags Genres
// @Accept  json
// @Produce  json
// @Param Genres body model.Genres true "Add Genres"
// @Success 200 {object} model.Genres
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /genres [post]
// echo '{"name": "hlRLqaFiXUwxNAwiIBQQgRULp","genre_id": 1}' | http POST "http://localhost:8080/genres" X-Api-User:user123
func AddGenres(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	genres := &model.Genres{}

	if err := readJSON(r, genres); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := genres.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	genres.Prepare()

	if err := genres.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "genres", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	genres, _, err = dao.AddGenres(ctx, genres)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, genres)
}

// UpdateGenres Update a single record from genres table in the main database
// @Summary Update an record in table genres
// @Description Update a single record from genres table in the main database
// @Tags Genres
// @Accept  json
// @Produce  json
// @Param  argGenreID path int true "GenreId"
// @Param  Genres body model.Genres true "Update Genres record"
// @Success 200 {object} model.Genres
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /genres/{argGenreID} [put]
// echo '{"name": "hlRLqaFiXUwxNAwiIBQQgRULp","genre_id": 1}' | http PUT "http://localhost:8080/genres/1"  X-Api-User:user123
func UpdateGenres(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argGenreID, err := parseInt32(ps, "argGenreID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	genres := &model.Genres{}
	if err := readJSON(r, genres); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := genres.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	genres.Prepare()

	if err := genres.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "genres", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	genres, _, err = dao.UpdateGenres(ctx,
		argGenreID,
		genres)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, genres)
}

// DeleteGenres Delete a single record from genres table in the main database
// @Summary Delete a record from genres
// @Description Delete a single record from genres table in the main database
// @Tags Genres
// @Accept  json
// @Produce  json
// @Param  argGenreID path int true "GenreId"
// @Success 204 {object} model.Genres
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /genres/{argGenreID} [delete]
// http DELETE "http://localhost:8080/genres/1" X-Api-User:user123
func DeleteGenres(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argGenreID, err := parseInt32(ps, "argGenreID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "genres", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteGenres(ctx, argGenreID)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
